﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Newtonsoft.Json.Linq;
using OfficeOpenXml.Drawing.Slicer.Style;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Drawing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using static AutoMapper.Internal.CollectionMapperExpressionFactory;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace Coldairarrow.Business.Interface
{
    public class Rep_InSalesStockInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        public List<OL_FilterDTO> Filters;
        public Rep_InSalesStockInterfaceBusiness()
        {
            this.InterfaceName = "1C进销存报表";
            //获取字段的映射关系
            tableField = GetMapField("editRow");
            //索引字段
            Keys = GetKeys("editRow");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();


            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //执行查询前添加过滤条件
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }

        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {
                //数据库连接
                ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

                //获取此接口的所有API信息
                this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
                Base_InterfaceOption queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
                Base_InterfaceOption insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
                Base_InterfaceOption upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
                Base_InterfaceOption deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置
                //需要获取期末数据的日期
                //string dateTo = DateTime.Now.AddMonths(-1).ToString("yyyy-MM");
                string dateTo = DateTime.Now.AddMonths(-queryOption.ExcInterval).ToString("yyyy-MM");
                //获取上月的进销存数据
                Filters.Clear();
                Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67da5875cd44971bbff19bf1", DataType = 15, SpliceType = 1, FilterType = 14, Value = dateTo }//FDATE字段过滤日开
            );
                //    Filters.Add(
                //    //13:>,14>=15:<,16<=
                //    new OL_FilterDTO() { ControlId = "67da5875cd44971bbff19bf1", DataType = 15, SpliceType = 1, FilterType = 15, Value = DateTime.Now.ToString("yyyy-MM") }//FDATE字段过滤日开
                //);

                List<Rep_InSalesStock> lastMonthData = await QueryAsync<Rep_InSalesStock>(queryOption, tableField, SqlDb);
                List<Rep_InSalesStock> sourceData = new List<Rep_InSalesStock>();
                List<Rep_InSalesStock> thisMonthData = new List<Rep_InSalesStock>();
                //生成源数据,用上个月的期末数据生成本月的期初数据
                if (!lastMonthData.IsNullOrEmpty() && lastMonthData.Count > 0)
                {
                    foreach (var item1 in lastMonthData)
                    {
                        //如果日期月份等于本月，不再新增
                        if (item1.date.ToDateTime().ToString("yyyy-MM") != DateTime.Now.ToString("yyyy-MM"))
                        {
                            Rep_InSalesStock temp = new Rep_InSalesStock();
                            temp.date = item1.date.ToDateTime().AddMonths(1).ToString("yyyy-MM");
                            temp.productName = item1.productName;
                            temp.productNo = item1.productNo;
                            temp.InitQty = item1.EndQty;
                            //temp.InitAmount = item1.EndAmount;
                            temp.InitUnitPrice = item1.EndUnitPrice;
                            temp.id = temp.date + temp.productName;
                            thisMonthData.Add(temp);
                        }
                    }
                }


                //采购入库数据设置
                thisMonthData = await SetProcurementCost(thisMonthData);
                //其他入库数据设置-物料变更调拨
                thisMonthData = await SetMaterialsChange(thisMonthData);
                //盘盈盘亏入库
                thisMonthData = await SetProfitLoss(thisMonthData);
                //销售出库数据设置
                thisMonthData = await SetSaleReport(thisMonthData);
                //其他出库数据设置-耗材支出
                thisMonthData = await SetMaterialsConstruction(thisMonthData);
                //其他出库数据设置-无偿转让
                thisMonthData = await SetFreeTransfer(thisMonthData);

                thisMonthData.ForEach(x =>
                {
                    if (x.id.IsNullOrEmpty()) x.id = x.date + x.productName;

                    //计算期末
                    var initQty = x.InitQty.IsNullOrEmpty() || x.InitQty.ToDouble() == 0 ? 0 : x.InitQty.ToDouble();
                    var initUnitPrice = x.InitUnitPrice.IsNullOrEmpty() || x.InitUnitPrice.ToDouble() == 0 ? 0 : x.InitUnitPrice.ToDouble();
                    //var initAmount = x.InitAmount.IsNullOrEmpty() || x.InitAmount.ToDouble() == 0 ? 0 : x.InitAmount.ToDouble();
                    var purQty = x.PurQty.IsNullOrEmpty() || x.PurQty.ToDouble() == 0 ? 0 : x.PurQty.ToDouble();
                    var purUnitPrice = x.PurUnitPrice.IsNullOrEmpty() || x.PurUnitPrice.ToDouble() == 0 ? 0 : x.PurUnitPrice.ToDouble();
                    //var purAmount = x.PurAmount.IsNullOrEmpty() || x.PurAmount.ToDouble() == 0 ? 0 : x.PurAmount.ToDouble();
                    //var otherInQty = x.OtherInQty.IsNullOrEmpty() || x.OtherInQty.ToDouble() == 0 ? 0 : x.OtherInQty.ToDouble();
                    //var otherInAmount = x.OtherInAmount.IsNullOrEmpty() || x.OtherInAmount.ToDouble() == 0 ? 0 : x.OtherInAmount.ToDouble();
                    //var saleQty = x.SaleQty.IsNullOrEmpty() || x.SaleQty.ToDouble() == 0 ? 0 : x.SaleQty.ToDouble();
                    //var saleAmount = x.SaleAmount.IsNullOrEmpty() || x.SaleAmount.ToDouble() == 0 ? 0 : x.SaleAmount.ToDouble();
                    //var otherOutQty = x.OtherOutQty.IsNullOrEmpty() || x.OtherOutQty.ToDouble() == 0 ? 0 : x.OtherOutQty.ToDouble();
                    //var otherOutAmount = x.OtherOutAmount.IsNullOrEmpty() || x.OtherOutAmount.ToDouble() == 0 ? 0 : x.OtherOutAmount.ToDouble();
                    //var unitPrice = CountUnitPrice(x);
                    //x.EndAmount = (initAmount + purAmount + otherInAmount - saleAmount - otherOutAmount).ToString("F2");
                    //x.EndQty = (initQty + purQty + otherInQty - saleQty - otherOutQty).ToString("F2");
                    //x.EndUnitPrice = unitPrice.ToString("F2");

                    //if ((initUnitPrice > 0 && initQty > 0) || (purUnitPrice > 0 && purQty > 0))
                    //{
                    //    x.costState = "正常";
                    //}
                    //else
                    //{
                    //    x.costState = "无期初/无成本";
                    //}
                    if (x.state.IsNullOrEmpty()) x.state = "无变动";



                });

                sourceData = thisMonthData;

                //获取目标数据
                dateTo = dateTo.ToDateTime().AddMonths(1).ToString("yyyy-MM");//需要获取更新数据的月份,比期末数据的月份大一个月
                Filters.Clear();
                Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67da5875cd44971bbff19bf1", DataType = 15, SpliceType = 1, FilterType = 14, Value = dateTo }//FDATE字段过滤日开
            );
                List<Rep_InSalesStock> targetData = await QueryAsync<Rep_InSalesStock>(queryOption, tableField, SqlDb);

                if (this.State > 0 && sourceData.Count > 0)
                {
                    //更新
                    #region
                    List<Rep_InSalesStock> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<Rep_InSalesStock>(Keys, "RowId")).ToList();//获取交集(更新项)
                    List<OL_RowDTO> updataData = ConvertOL_Row(updataItem, tableField);//需要更新的数据集合
                    ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                    #endregion

                    //新增
                    #region
                    List<Rep_InSalesStock> insertItem = sourceData.Except(targetData, new ComparerFromKey<Rep_InSalesStock>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                    List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                    ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                    #endregion

                    //删除
                    #region
                    List<Rep_InSalesStock> deleteItem = targetData.Except(sourceData, new ComparerFromKey<Rep_InSalesStock>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)
                    List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                    ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行
                    #endregion
                }
            }


            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }




        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //获取字段的键值做判断
                    var field = Keys.Where(x => x.TField == c.Key).ToList();
                    string isKey = "";
                    if (field.Count > 0) isKey = field.First().Type;
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value) && isKey != "N")
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }


        /// <summary>
        /// 设置采购入库价格数量
        /// </summary>
        /// <param name="thisMonthData">本月数据</param>
        /// <returns></returns>
        public async Task<List<Rep_InSalesStock>> SetProcurementCost(List<Rep_InSalesStock> thisMonthData)
        {
            var monthGroup = thisMonthData.GroupBy(x => x.date);
            //List<Rep_InSalesStock> thisMonthData_set = new List<Rep_InSalesStock>();
            foreach (var item1 in monthGroup)
            {
                string monthFrom = item1.Key + "-01";
                string monthTo = monthFrom.ToDateTime().GetLastDay().ToString("yyyy-MM-dd");

                Rep_ProcurementCostInterfaceBusiness rep_ProcurementCost = new Rep_ProcurementCostInterfaceBusiness();
                //获取对应时间的采购成本
                rep_ProcurementCost.Filters.Clear();
                rep_ProcurementCost.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d932aacd44971bbfdcf804", DataType = 15, SpliceType = 1, FilterType = 14, Value = monthFrom }//FDATE字段过滤日开
            ); rep_ProcurementCost.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d932aacd44971bbfdcf804", DataType = 15, SpliceType = 1, FilterType = 16, Value = monthTo }//FDATE字段过滤日开
            );
                List<Rep_ProcurementCost> purList = await rep_ProcurementCost.QueryAsync<Rep_ProcurementCost>(rep_ProcurementCost.queryOption, rep_ProcurementCost.tableField, rep_ProcurementCost.SqlDb);

                //将对应时间采购成本的字段值设置到当月的进销存表中
                foreach (var purItem in purList)
                {
                    //获取进销存对应物料的项
                    var stockList = thisMonthData.Where(x => x.productName == purItem.productName && x.date == purItem.date.ToDateTime().ToString("yyyy-MM"));
                    //正常有数量的采购订单
                    if (purItem.count.ToDouble() > 0 && purItem.cost.ToDouble() > 0)
                    {
                        //如果存在,设置对应的值
                        if (!stockList.IsNullOrEmpty() && stockList.Count() > 0)
                        {
                            var stockItem = stockList.First();
                            thisMonthData.RemoveAll(x => x.productName == stockItem.productName && x.date == purItem.date.ToDateTime().ToString("yyyy-MM"));
                            //合计
                            stockItem.PurQty = purItem.count;
                            stockItem.PurUnitPrice = purItem.cost;
                            //stockItem.PurAmount = purItem.amount;
                            stockItem.state = "变动";
                            thisMonthData.Add(stockItem);
                        }
                        //如果不存在,新增一行
                        else
                        {
                            Rep_InSalesStock newItem = new Rep_InSalesStock();
                            newItem.date = purItem.date.ToDateTime().ToString("yyyy-MM");
                            newItem.productName = purItem.productName;
                            newItem.productNo = purItem.productNo;
                            newItem.PurQty = purItem.count;
                            newItem.PurUnitPrice = purItem.cost;
                            //newItem.PurAmount = purItem.amount;
                            newItem.state = "新增";
                            thisMonthData.Add(newItem);
                        }
                    }
                    //跨月有费用没有数量的费用
                    else
                    {
                        //如果存在,设置对应的值
                        if (!stockList.IsNullOrEmpty() && stockList.Count() > 0)
                        {
                            var stockItem1 = stockList.First();
                            thisMonthData.RemoveAll(x => x.productName == stockItem1.productName && x.date == purItem.date.ToDateTime().ToString("yyyy-MM"));
                            //设置费用
                            var PurAcrossMonthAmount = stockItem1.PurAcrossMonthAmount.IsNullOrEmpty() || stockItem1.PurAcrossMonthAmount.ToDouble() == 0 ? 0 : stockItem1.PurAcrossMonthAmount.ToDouble();
                            var amount = purItem.cost.IsNullOrEmpty() || purItem.amount.ToDouble() == 0 ? 0 : purItem.amount.ToDouble();
                            stockItem1.PurAcrossMonthAmount = (amount + PurAcrossMonthAmount).ToString("F2");
                            stockItem1.state = "变动";
                            thisMonthData.Add(stockItem1);
                        }
                        //如果不存在,新增一行
                        else
                        {
                            Rep_InSalesStock newItem = new Rep_InSalesStock();
                            newItem.date = purItem.date.ToDateTime().ToString("yyyy-MM");
                            newItem.productName = purItem.productName;
                            newItem.PurAcrossMonthAmount = purItem.amount;
                            //newItem.PurAmount = purItem.amount;
                            newItem.state = "新增";
                            thisMonthData.Add(newItem);
                        }

                    }

                }

            }
            return thisMonthData;
        }


        /// <summary>
        /// 其他入库数据设置-物料变更调拨
        /// </summary>
        /// <param name="thisMonthData">本月数据</param>
        /// <returns></returns>
        public async Task<List<Rep_InSalesStock>> SetMaterialsChange(List<Rep_InSalesStock> thisMonthData)
        {
            var monthGroup = thisMonthData.GroupBy(x => x.date);
            //List<Rep_InSalesStock> thisMonthData_set = new List<Rep_InSalesStock>();
            foreach (var item1 in monthGroup)
            {
                string monthFrom = item1.Key + "-01";
                string monthTo = monthFrom.ToDateTime().GetLastDay().ToString("yyyy-MM-dd");

                Rep_MaterialsChangeInterfaceBusiness rep_MaterialsChange = new Rep_MaterialsChangeInterfaceBusiness();
                //获取对应时间的物料变更调拨
                rep_MaterialsChange.Filters.Clear();
                rep_MaterialsChange.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d28967cd44971bbf4ded09", DataType = 15, SpliceType = 1, FilterType = 14, Value = monthFrom }//FDATE字段过滤日开
            ); rep_MaterialsChange.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d28967cd44971bbf4ded09", DataType = 15, SpliceType = 1, FilterType = 16, Value = monthTo }//FDATE字段过滤日开
            );
                List<Rep_MaterialsChange> matList = await rep_MaterialsChange.QueryAsync<Rep_MaterialsChange>(rep_MaterialsChange.queryOption, rep_MaterialsChange.tableField, rep_MaterialsChange.SqlDb);

                //将对应时间物料变更调拨的字段值设置到当月的进销存表中
                foreach (var matItem in matList)
                {

                    #region 设置进销存原物料
                    //获取进销存对应原来物料的项
                    var stockItem_s = thisMonthData.Where(x => x.productName == matItem.productName_s && x.date == matItem.date.ToDateTime().ToString("yyyy-MM"));
                    var unitPrice_s = 0.0;
                    //如果存在,设置对应的值
                    if (!stockItem_s.IsNullOrEmpty() && stockItem_s.Count() > 0)
                    {
                        var stockItem = stockItem_s.First();
                        thisMonthData.RemoveAll(x => x.productName == stockItem.productName && x.date == stockItem.date.ToDateTime().ToString("yyyy-MM"));

                        //设置调拨数量
                        var qty = matItem.qty.ToDouble() * -1;
                        var nameChangeQty = stockItem.NameChangeQty.IsNullOrEmpty() || stockItem.NameChangeQty.ToDouble() == 0 ? 0 : stockItem.NameChangeQty.ToDouble();
                        stockItem.NameChangeQty = (qty + nameChangeQty).ToString();
                        //有采购单价去采购没有取期初单价
                        //var unitPrice = CountUnitPrice(stockItem); //计算期初及采购成本的平均价格
                        //unitPrice_s = unitPrice;
                        //stockItem.OtherInUnitPrice = unitPrice.ToString("F2");
                        //计算总金额
                        //stockItem.OtherInAmount = (unitPrice * (qty + otherInQty)).ToString("F2");
                        stockItem.state = stockItem.state.IsNullOrEmpty() || stockItem.state != "新增" ? "变动" : stockItem.state;
                        thisMonthData.Add(stockItem);
                    }
                    //如果不存在,新增一行
                    else
                    {
                        Rep_InSalesStock newItem = new Rep_InSalesStock();
                        newItem.date = matItem.date.ToDateTime().ToString("yyyy-MM");
                        newItem.productName = matItem.productName_s;
                        newItem.productNo = matItem.productNo_s;
                        var qty = matItem.qty.ToDouble() * -1;
                        newItem.NameChangeQty = qty.ToString();
                        //newItem.PurUnitPrice = purItem.amount;
                        //newItem.PurAmount = purItem.cost;
                        newItem.state = "新增";
                        thisMonthData.Add(newItem);
                    }
                    #endregion

                    #region 设置进销存新物料
                    var stockItem_n = thisMonthData.Where(x => x.productName == matItem.productName_n && x.date == matItem.date.ToDateTime().ToString("yyyy-MM"));
                    //如果存在,设置对应的值
                    if (!stockItem_n.IsNullOrEmpty() && stockItem_n.Count() > 0)
                    {
                        var stockItem1 = stockItem_n.First();
                        thisMonthData.RemoveAll(x => x.productName == stockItem1.productName && x.date == stockItem1.date.ToDateTime().ToString("yyyy-MM"));
                        //设置调拨数量
                        var qty = matItem.qty.ToDouble();
                        var nameChangeQty = stockItem1.NameChangeQty.IsNullOrEmpty() || stockItem1.NameChangeQty.ToDouble() == 0 ? 0 : stockItem1.NameChangeQty.ToDouble();
                        stockItem1.NameChangeQty = (qty + nameChangeQty).ToString();
                        //计算总金额(原有的金额，加上变更前物料单价*新增数量)
                        //var amount = qty * unitPrice_s;
                        //var amount_ = stockItem1.OtherInAmount.IsNullOrEmpty() || stockItem1.OtherInAmount.ToDouble() == 0 ? 0 : stockItem1.OtherInAmount.ToDouble();
                        //stockItem1.OtherInAmount = (amount_ + amount).ToString("F2");


                        //var unitPrice = 0.0;
                        //如果新增的总金额为0,则取默认期初，如果有取加权平均
                        //if (amount == 0)
                        //{
                        //    //计算期初及采购成本的平均价格
                        //    unitPrice = CountUnitPrice(stockItem1);
                        //}
                        //else
                        //{
                        //    unitPrice = (qty + otherInQty) == 0 ? 0 : (amount_ + amount) / (qty + otherInQty);
                        //}

                        //stockItem1.OtherInUnitPrice = unitPrice.ToString("F2");
                        stockItem1.state = stockItem1.state.IsNullOrEmpty() || stockItem1.state != "新增" ? "变动" : stockItem1.state;
                        thisMonthData.Add(stockItem1);
                    }
                    //如果不存在,新增一行
                    else
                    {

                        Rep_InSalesStock newItem = new Rep_InSalesStock();
                        newItem.date = matItem.date.ToDateTime().ToString("yyyy-MM");
                        newItem.productName = matItem.productName_n;
                        newItem.productNo = matItem.productNo_n;
                        newItem.NameChangeQty = matItem.qty;
                        //获取变更前的物料的采购单价和期初单价
                        var stock_s = thisMonthData.Where(x => x.productName == stockItem_s.First().productName);
                        var stock_s_ = !stock_s.IsNullOrEmpty() && stock_s.Count() > 0 ? stock_s.First() : null;
                        if (!stock_s_.IsNullOrEmpty())
                        {
                            //使用变更前物料的单价
                            //var unitPrice = CountUnitPrice(stock_s_);
                            //newItem.OtherInUnitPrice = unitPrice.ToString("F2");
                            //设置数量
                            var qty = matItem.qty.ToDouble();
                            //设置总金额
                            //newItem.OtherInAmount = (unitPrice * qty).ToString("F2");
                        }
                        newItem.state = "新增";
                        thisMonthData.Add(newItem);
                    }
                    #endregion
                }

            }
            return thisMonthData;
        }



        /// <summary>
        /// 盘盈盘亏入库
        /// </summary>
        /// <param name="thisMonthData">本月数据</param>
        /// <returns></returns>
        public async Task<List<Rep_InSalesStock>> SetProfitLoss(List<Rep_InSalesStock> thisMonthData)
        {
            var monthGroup = thisMonthData.GroupBy(x => x.date);
            //List<Rep_InSalesStock> thisMonthData_set = new List<Rep_InSalesStock>();
            foreach (var item1 in monthGroup)
            {
                string monthFrom = item1.Key + "-01";
                string monthTo = monthFrom.ToDateTime().GetLastDay().ToString("yyyy-MM-dd");
                //获取金蝶俄罗斯汇率
                SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:K3ConnectionString");
                List<View_Rate> KD_Rate = SqlDb.GetListBySql<View_Rate>(@$"SELECT * FROM  V_WW_BD_Rate(NOLOCK) WHERE 汇率类型 = '俄罗斯专用' ");
                var KD_rate_ = KD_Rate.Where(x => x.生效时间.ToDateTime().ToString("yyyy-MM-dd").ToDateTime() <= monthFrom.ToDateTime().ToString("yyyy-MM-dd").ToDateTime() && monthFrom.ToDateTime() <= x.失效时间.ToDateTime().ToString("yyyy-MM-dd").ToDateTime());
                var rate = !KD_rate_.IsNullOrEmpty() && KD_rate_.Count() > 0 ? KD_rate_.First().间接汇率.ToDouble() : 0;

                //获取序时账列表
                Rep_ChronologicalAccountInterfaceBusiness Rep_ChronologicalAccount = new Rep_ChronologicalAccountInterfaceBusiness();
                Rep_ChronologicalAccount.Filters.Clear();
                Rep_ChronologicalAccount.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d11f12cd44971bbf2bebf5", DataType = 15, SpliceType = 1, FilterType = 14, Value = monthFrom }//FDATE字段过滤日开
            );
                Rep_ChronologicalAccount.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d11f12cd44971bbf2bebf5", DataType = 15, SpliceType = 1, FilterType = 16, Value = monthTo }//FDATE字段过滤日开
            );
            //    Rep_ChronologicalAccount.Filters.Add(
            //    //13:>,14>=15:<,16<=
            //    new OL_FilterDTO() { ControlId = "67d0fcbdcd44971bbf2842ad", DataType = 2, SpliceType = 1, FilterType = 1, Value = "Оприходование товаров" }//获取费用来源为盘盈盘亏
            //);
                Rep_ChronologicalAccount.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d0fcbdcd44971bbf2842af", DataType = 2, SpliceType = 1, FilterType = 2, Value = "41.01" }//借方会记科目
            );
                Rep_ChronologicalAccount.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d0fcbdcd44971bbf2842b7", DataType = 2, SpliceType = 1, FilterType = 2, Value = "91.01" }//贷方会记科目
            );
                List<Rep_ChronologicalAccount> Rep_ChronAccount = await Rep_ChronologicalAccount.QueryAsync<Rep_ChronologicalAccount>(Rep_ChronologicalAccount.queryOption, Rep_ChronologicalAccount.tableField, Rep_ChronologicalAccount.SqlDb);

                //将对应时间物料变更调拨的字段值设置到当月的进销存表中
                foreach (var item in Rep_ChronAccount)
                {

                    //获取进销存对应原来物料的项
                    var stockItems = thisMonthData.Where(x => x.productName == item.debitAnalytic1 && x.date == item.date.ToDateTime().ToString("yyyy-MM"));

                    //如果存在,设置对应的值
                    if (!stockItems.IsNullOrEmpty() && stockItems.Count() > 0)
                    {
                        var stockItem = stockItems.First();
                        thisMonthData.RemoveAll(x => x.productName == stockItem.productName && x.date == stockItem.date.ToDateTime().ToString("yyyy-MM"));

                        //设置调拨数量
                        var qty = item.debitCount.ToDouble();
                        var otherInQty = stockItem.OtherInQty.IsNullOrEmpty() || stockItem.OtherInQty.ToDouble() == 0 ? 0 : stockItem.OtherInQty.ToDouble();
                        stockItem.OtherInQty = (qty + otherInQty).ToString();

                        //计算总金额
                        //var amount = item.Amount.ToDouble() / rate;
                        //var otherInAmount = stockItem.OtherInAmount.IsNullOrEmpty() || stockItem.OtherInAmount.ToDouble() == 0 ? 0 : stockItem.OtherInAmount.ToDouble();
                        //stockItem.OtherInAmount = (amount + otherInAmount).ToString("F2");

                        //有采购单价去采购没有取期初单价
                        //var unitPrice = stockItem.OtherInQty.ToDouble() == 0 ? 0 : stockItem.OtherInAmount.ToDouble() / stockItem.OtherInQty.ToDouble(); //计算单价
                        //stockItem.OtherInUnitPrice = unitPrice.ToString("F2");
                        stockItem.state = stockItem.state.IsNullOrEmpty() || stockItem.state != "新增" ? "变动" : stockItem.state;
                        thisMonthData.Add(stockItem);
                    }
                    //如果不存在,新增一行
                    else
                    {
                        Rep_InSalesStock newItem = new Rep_InSalesStock();
                        newItem.date = item.date.ToDateTime().ToString("yyyy-MM");
                        newItem.productName = item.debitAnalytic1;
                        var qty = item.debitCount.ToDouble();
                        //var amount = item.Amount.ToDouble() / rate;
                        //var unitPrice = amount / qty;
                        newItem.OtherInQty = qty.ToString();
                        //newItem.OtherInAmount = amount.ToString();
                        //newItem.OtherInUnitPrice = unitPrice.ToString();

                        newItem.state = "新增";
                        thisMonthData.Add(newItem);
                    }

                }

            }
            return thisMonthData;
        }

        /// <summary>
        /// 设置销售出库价格数量
        /// </summary>
        /// <param name="thisMonthData">本月数据</param>
        /// <returns></returns>
        public async Task<List<Rep_InSalesStock>> SetSaleReport(List<Rep_InSalesStock> thisMonthData)
        {
            var monthGroup = thisMonthData.GroupBy(x => x.date);
            //List<Rep_InSalesStock> thisMonthData_set = new List<Rep_InSalesStock>();
            foreach (var item1 in monthGroup)
            {
                string monthFrom = item1.Key + "-01";
                string monthTo = monthFrom.ToDateTime().GetLastDay().ToString("yyyy-MM-dd");

                Rep_1CSaleReportInterfaceBusiness rep_1CSaleReport = new Rep_1CSaleReportInterfaceBusiness();
                //获取对应时间的销售出库
                rep_1CSaleReport.Filters.Clear();
                rep_1CSaleReport.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d28967cd44971bbf4ded09", DataType = 15, SpliceType = 1, FilterType = 14, Value = monthFrom }//FDATE字段过滤日开
            ); rep_1CSaleReport.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d28967cd44971bbf4ded09", DataType = 15, SpliceType = 1, FilterType = 16, Value = monthTo }//FDATE字段过滤日开
            );
                List<Rep_1CSaleReport> saleList = await rep_1CSaleReport.QueryAsync<Rep_1CSaleReport>(rep_1CSaleReport.queryOption, rep_1CSaleReport.tableField, rep_1CSaleReport.SqlDb);

                //将对应时间采购成本的字段值设置到当月的进销存表中
                foreach (var saleItem in saleList)
                {
                    //获取进销存对应物料的项
                    var stockList = thisMonthData.Where(x => x.productName == saleItem.productName && x.date == saleItem.date.ToDateTime().ToString("yyyy-MM"));

                    //如果存在,设置对应的值
                    if (!stockList.IsNullOrEmpty() && stockList.Count() > 0)
                    {
                        var stockItem = stockList.First();
                        thisMonthData.RemoveAll(x => x.productName == stockItem.productName && x.date == stockItem.date.ToDateTime().ToString("yyyy-MM"));

                        //设置销售数量
                        var qty = saleItem.qty.ToDouble();
                        var saleQty = stockItem.SaleQty.IsNullOrEmpty() || stockItem.SaleQty.ToDouble() == 0 ? 0 : stockItem.SaleQty.ToDouble();
                        stockItem.SaleQty = (qty + saleQty).ToString();

                        //设置销售单价
                        //var unitPrice = CountUnitPrice(stockItem);  //计算期初及采购成本的平均价格
                        //stockItem.SaleUnitPrice = unitPrice.ToString("F2");

                        //设置销售总价
                        //stockItem.SaleAmount = (unitPrice * (qty + saleQty)).ToString("F2");
                        stockItem.state = stockItem.state.IsNullOrEmpty() || stockItem.state != "新增" ? "变动" : stockItem.state;
                        thisMonthData.Add(stockItem);
                    }
                    //如果不存在,新增一行
                    else
                    {
                        Rep_InSalesStock newItem = new Rep_InSalesStock();
                        newItem.date = saleItem.date.ToDateTime().ToString("yyyy-MM");
                        newItem.productName = saleItem.productName;
                        newItem.productNo = saleItem.productNo;
                        newItem.SaleQty = saleItem.qty;
                        newItem.state = "新增";
                        //newItem.SaleUnitPrice = purItem.amount;
                        //newItem.SaleAmount = purItem.cost;
                        thisMonthData.Add(newItem);
                    }
                }

            }
            return thisMonthData;
        }

        /// <summary>
        /// 其他出库数据设置-耗材支出
        /// </summary>
        /// <param name="thisMonthData">本月数据</param>
        /// <returns></returns>
        public async Task<List<Rep_InSalesStock>> SetMaterialsConstruction(List<Rep_InSalesStock> thisMonthData)
        {
            var monthGroup = thisMonthData.GroupBy(x => x.date);
            //List<Rep_InSalesStock> thisMonthData_set = new List<Rep_InSalesStock>();
            foreach (var item1 in monthGroup)
            {
                string monthFrom = item1.Key + "-01";
                string monthTo = monthFrom.ToDateTime().GetLastDay().ToString("yyyy-MM-dd");

                Rep_MaterialsConstructionInterfaceBusiness Rep_MaterialsConstruction = new Rep_MaterialsConstructionInterfaceBusiness();
                //获取对应时间的耗材支出
                Rep_MaterialsConstruction.Filters.Clear();
                Rep_MaterialsConstruction.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d28967cd44971bbf4ded09", DataType = 15, SpliceType = 1, FilterType = 14, Value = monthFrom }//FDATE字段过滤日开
            ); Rep_MaterialsConstruction.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d28967cd44971bbf4ded09", DataType = 15, SpliceType = 1, FilterType = 16, Value = monthTo }//FDATE字段过滤日开
            );
                List<Rep_1CSaleReport> constList = await Rep_MaterialsConstruction.QueryAsync<Rep_1CSaleReport>(Rep_MaterialsConstruction.queryOption, Rep_MaterialsConstruction.tableField, Rep_MaterialsConstruction.SqlDb);

                //将对应时间采购成本的字段值设置到当月的进销存表中
                foreach (var constItem in constList)
                {
                    if (constItem.productName == "Прессостат 60/75 Па AA.03.05.0023")
                    {
                        var test = "";
                    
                    }
                    //获取进销存对应物料的项
                    var stockList = thisMonthData.Where(x => x.productName == constItem.productName && x.date == constItem.date.ToDateTime().ToString("yyyy-MM"));

                    //如果存在,设置对应的值
                    if (!stockList.IsNullOrEmpty() && stockList.Count() > 0)
                    {
                        var stockItem = stockList.First();
                        thisMonthData.RemoveAll(x => x.productName == stockItem.productName && x.date == stockItem.date.ToDateTime().ToString("yyyy-MM"));


                        //设置数量
                        var qty = constItem.qty.ToDouble();
                        var otherOutQty = stockItem.OtherOutQty.IsNullOrEmpty() || stockItem.OtherOutQty.ToDouble() == 0 ? 0 : stockItem.OtherOutQty.ToDouble();
                        stockItem.OtherOutQty = (qty + otherOutQty).ToString();


                        //设置销售单价
                        //var unitPrice = CountUnitPrice(stockItem);  //计算期初及采购成本的平均价格
                        //stockItem.OtherOutUnitPrice = unitPrice.ToString("F2");

                        //设置销售总价
                        //stockItem.OtherOutAmount = (unitPrice * (qty + otherOutQty)).ToString("F2");
                        stockItem.state = stockItem.state.IsNullOrEmpty() || stockItem.state != "新增" ? "变动" : stockItem.state;
                        thisMonthData.Add(stockItem);
                    }
                    //如果不存在,新增一行
                    else
                    {
                        Rep_InSalesStock newItem = new Rep_InSalesStock();
                        newItem.date = constItem.date.ToDateTime().ToString("yyyy-MM");
                        newItem.productName = constItem.productName;
                        newItem.productNo = constItem.productNo;
                        newItem.OtherOutQty = constItem.qty;
                        //newItem.OtherOutUnitPrice = purItem.amount;
                        //newItem.OtherOutAmount = purItem.cost;
                        newItem.state = "新增";
                        thisMonthData.Add(newItem);
                    }
                }

            }
            return thisMonthData;
        }



        /// <summary>
        /// 其他出库数据设置-无偿转让
        /// </summary>
        /// <param name="thisMonthData">本月数据</param>
        /// <returns></returns>
        public async Task<List<Rep_InSalesStock>> SetFreeTransfer(List<Rep_InSalesStock> thisMonthData)
        {
            var monthGroup = thisMonthData.GroupBy(x => x.date);
            //List<Rep_InSalesStock> thisMonthData_set = new List<Rep_InSalesStock>();
            foreach (var item1 in monthGroup)
            {
                string monthFrom = item1.Key + "-01";
                string monthTo = monthFrom.ToDateTime().GetLastDay().ToString("yyyy-MM-dd");
                //获取金蝶俄罗斯汇率
                SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:K3ConnectionString");
                List<View_Rate> KD_Rate = SqlDb.GetListBySql<View_Rate>(@$"SELECT * FROM  V_WW_BD_Rate(NOLOCK) WHERE 汇率类型 = '俄罗斯专用' ");
                var KD_rate_ = KD_Rate.Where(x => x.生效时间.ToDateTime().ToString("yyyy-MM-dd").ToDateTime() <= monthFrom.ToDateTime().ToString("yyyy-MM-dd").ToDateTime() && monthFrom.ToDateTime() <= x.失效时间.ToDateTime().ToString("yyyy-MM-dd").ToDateTime());
                var rate = !KD_rate_.IsNullOrEmpty() && KD_rate_.Count() > 0 ? KD_rate_.First().间接汇率.ToDouble() : 0;

                //获取序时账列表
                Rep_ChronologicalAccountInterfaceBusiness Rep_ChronologicalAccount = new Rep_ChronologicalAccountInterfaceBusiness();
                Rep_ChronologicalAccount.Filters.Clear();
                Rep_ChronologicalAccount.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d11f12cd44971bbf2bebf5", DataType = 15, SpliceType = 1, FilterType = 14, Value = monthFrom }//FDATE字段过滤日开
            );
                Rep_ChronologicalAccount.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d11f12cd44971bbf2bebf5", DataType = 15, SpliceType = 1, FilterType = 16, Value = monthTo }//FDATE字段过滤日开
            );
                //    Rep_ChronologicalAccount.Filters.Add(
                //    //13:>,14>=15:<,16<=
                //    new OL_FilterDTO() { ControlId = "67d0fcbdcd44971bbf2842ad", DataType = 2, SpliceType = 1, FilterType = 1, Value = "Оприходование товаров" }//获取费用来源为盘盈盘亏
                //);
                Rep_ChronologicalAccount.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d0fcbdcd44971bbf2842af", DataType = 2, SpliceType = 1, FilterType = 2, Value = "91.02" }//借方会记科目
            );
                Rep_ChronologicalAccount.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d0fcbdcd44971bbf2842b7", DataType = 2, SpliceType = 1, FilterType = 2, Value = "41.01" }//贷方会记科目
            );
                Rep_ChronologicalAccount.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d0fcbdcd44971bbf2842ad", DataType = 2, SpliceType = 1, FilterType = 1, Value = "Передача товаров" }//费用来源包含
            );
                List<Rep_ChronologicalAccount> Rep_ChronAccount = await Rep_ChronologicalAccount.QueryAsync<Rep_ChronologicalAccount>(Rep_ChronologicalAccount.queryOption, Rep_ChronologicalAccount.tableField, Rep_ChronologicalAccount.SqlDb);






                //将对应时间采购成本的字段值设置到当月的进销存表中
                foreach (var constItem in Rep_ChronAccount)
                {
                    //获取进销存对应物料的项
                    var stockList = thisMonthData.Where(x => x.productName == constItem.creditAnalytic1 && x.date == constItem.date.ToDateTime().ToString("yyyy-MM"));

                    //如果存在,设置对应的值
                    if (!stockList.IsNullOrEmpty() && stockList.Count() > 0)
                    {
                        var stockItem = stockList.First();
                        thisMonthData.RemoveAll(x => x.productName == stockItem.productName && x.date == stockItem.date.ToDateTime().ToString("yyyy-MM"));


                        //设置数量
                        var qty = constItem.creditCount.ToDouble();
                        var otherOutQty = stockItem.OtherOutQty.IsNullOrEmpty() || stockItem.OtherOutQty.ToDouble() == 0 ? 0 : stockItem.OtherOutQty.ToDouble();
                        stockItem.OtherOutQty = (qty + otherOutQty).ToString();


                        //设置销售单价
                        //var unitPrice = CountUnitPrice(stockItem);  //计算期初及采购成本的平均价格
                        //stockItem.OtherOutUnitPrice = unitPrice.ToString("F2");

                        //设置销售总价
                        //stockItem.OtherOutAmount = (unitPrice * (qty + otherOutQty)).ToString("F2");
                        stockItem.state = stockItem.state.IsNullOrEmpty() || stockItem.state != "新增" ? "变动" : stockItem.state;
                        thisMonthData.Add(stockItem);
                    }
                    //如果不存在,新增一行
                    else
                    {
                        Rep_InSalesStock newItem = new Rep_InSalesStock();
                        newItem.date = constItem.date.ToDateTime().ToString("yyyy-MM");
                        newItem.productName = constItem.creditAnalytic1;
                        newItem.productNo = "";
                        newItem.OtherOutQty = constItem.creditCount;
                        //newItem.OtherOutUnitPrice = purItem.amount;
                        //newItem.OtherOutAmount = purItem.cost;
                        newItem.state = "新增";
                        thisMonthData.Add(newItem);
                    }
                }

            }
            return thisMonthData;
        }



        /// <summary>
        /// 物料名称调拨_计算期初和采购成本的平均单价
        /// </summary>
        /// <param name="stockItem"></param>
        /// <returns></returns>
        //private double CountUnitPrice(Rep_InSalesStock stockItem, Rep_InSalesStock thisMonth)
        //{
        //    //计算期初及采购成本的平均价格
        //    var initQty = stockItem.InitQty.IsNullOrEmpty() || stockItem.InitQty.ToDouble() == 0 ? 0 : stockItem.InitQty.ToDouble();
        //    var initUnitPrice = stockItem.InitUnitPrice.IsNullOrEmpty() || stockItem.InitUnitPrice.ToDouble() == 0 ? 0 : stockItem.InitUnitPrice.ToDouble();
        //    var initAmount = stockItem.InitAmount.IsNullOrEmpty() || stockItem.InitAmount.ToDouble() == 0 ? 0 : stockItem.InitAmount.ToDouble();
        //    var purQty = stockItem.PurQty.IsNullOrEmpty() || stockItem.PurQty.ToDouble() == 0 ? 0 : stockItem.PurQty.ToDouble();
        //    var purUnitPrice = stockItem.PurUnitPrice.IsNullOrEmpty() || stockItem.PurUnitPrice.ToDouble() > 0 ? 0 : stockItem.PurUnitPrice.ToDouble();
        //    var purAmount = stockItem.PurAmount.IsNullOrEmpty() || stockItem.PurAmount.ToDouble() == 0 ? 0 : stockItem.PurAmount.ToDouble();

        //    var otherInQty = stockItem.OtherInQty.IsNullOrEmpty() || stockItem.OtherInQty.ToDouble() == 0 ? 0 : stockItem.OtherInQty.ToDouble();
        //    var otherInUnitPrice = stockItem.OtherInUnitPrice.IsNullOrEmpty() || stockItem.OtherInUnitPrice.ToDouble() > 0 ? 0 : stockItem.OtherInUnitPrice.ToDouble();
        //    var otherInAmount = otherInQty * otherInUnitPrice;

        //    var initQty_Set = stockItem.InitQty_Set.IsNullOrEmpty() || stockItem.InitQty_Set.ToDouble() == 0 ? 0 : stockItem.InitQty_Set.ToDouble();
        //    var initUnitPrice_Set = stockItem.InitUnitPrice_Set.IsNullOrEmpty() || stockItem.InitUnitPrice_Set.ToDouble() > 0 ? 0 : stockItem.InitUnitPrice_Set.ToDouble();
        //    //var initUnitAmount_Set = initQty_Set * initUnitPrice_Set;
        //    double unitPrice = 0;
        //    //都有价格和数量取加权平均
        //    //if (initAmount > 0 && purAmount > 0 && initQty > 0 && purQty > 0)
        //    //{
        //    //    unitPrice = (initAmount + purAmount) / (purQty + initQty);
        //    //}
        //    ////期初没数量，取采购
        //    //else if (initQty == 0 && purQty > 0 && purAmount > 0)
        //    //{
        //    //    unitPrice = purAmount / purQty;
        //    //}
        //    ////采购没数量，取期初
        //    //else if (purQty == 0 && initQty > 0 && initAmount > 0)
        //    //{
        //    //    unitPrice = initAmount / initQty;
        //    //}

        //    unitPrice = (purQty + initQty + otherInQty + initQty_Set) == 0 ? 0 : (initAmount + purAmount + otherInAmount) / (purQty + initQty + otherInQty + initQty_Set);
        //    //if (initUnitPrice_Set == 0)
        //    //{
        //    //    unitPrice = (purQty + initQty + otherInQty + initQty_Set) == 0 ? 0 : (initAmount + purAmount + otherInAmount) / (purQty + initQty + otherInQty + initQty_Set);

        //    //}
        //    //else 
        //    //{
        //    //    unitPrice = (purQty + initQty + otherInQty + initQty_Set) == 0 ? 0 : (initAmount + purAmount + otherInAmount) / (purQty + initQty + otherInQty + initQty_Set);
        //    //}

        //    return unitPrice;
        //}


        /// <summary>
        /// 计算期初和采购成本的平均单价
        /// </summary>
        /// <param name="stockItem"></param>
        /// <returns></returns>
        //private double CountUnitPrice(Rep_InSalesStock stockItem)
        //{
        //    //计算期初及采购成本的平均价格
        //    var initQty = stockItem.InitQty.IsNullOrEmpty() || stockItem.InitQty.ToDouble() == 0 ? 0 : stockItem.InitQty.ToDouble();
        //    var initUnitPrice = stockItem.InitUnitPrice.IsNullOrEmpty() || stockItem.InitUnitPrice.ToDouble() == 0 ? 0 : stockItem.InitUnitPrice.ToDouble();
        //    var initAmount = initQty * initUnitPrice;
        //    var purQty = stockItem.PurQty.IsNullOrEmpty() || stockItem.PurQty.ToDouble() == 0 ? 0 : stockItem.PurQty.ToDouble();
        //    var purUnitPrice = stockItem.PurUnitPrice.IsNullOrEmpty() || stockItem.PurUnitPrice.ToDouble() > 0 ? 0 : stockItem.PurUnitPrice.ToDouble();
        //    var purAmount = purQty * purUnitPrice;

        //    var otherInQty = stockItem.OtherInQty.IsNullOrEmpty() || stockItem.OtherInQty.ToDouble() == 0 ? 0 : stockItem.OtherInQty.ToDouble();
        //    var otherInUnitPrice = stockItem.OtherInUnitPrice.IsNullOrEmpty() || stockItem.OtherInUnitPrice.ToDouble() > 0 ? 0 : stockItem.OtherInUnitPrice.ToDouble();
        //    var otherInAmount = otherInQty * otherInUnitPrice;

        //    var initQty_Set = stockItem.InitQty_Set.IsNullOrEmpty() || stockItem.InitQty_Set.ToDouble() == 0 ? 0 : stockItem.InitQty_Set.ToDouble();
        //    var initUnitPrice_Set = stockItem.InitUnitPrice_Set.IsNullOrEmpty() || stockItem.InitUnitPrice_Set.ToDouble() > 0 ? 0 : stockItem.InitUnitPrice_Set.ToDouble();
        //    var initUnitAmount_Set = initQty_Set * initUnitPrice_Set;
        //    double unitPrice = 0;
        //    //都有价格和数量取加权平均
        //    //if (initAmount > 0 && purAmount > 0 && initQty > 0 && purQty > 0)
        //    //{
        //    //    unitPrice = (initAmount + purAmount) / (purQty + initQty);
        //    //}
        //    ////期初没数量，取采购
        //    //else if (initQty == 0 && purQty > 0 && purAmount > 0)
        //    //{
        //    //    unitPrice = purAmount / purQty;
        //    //}
        //    ////采购没数量，取期初
        //    //else if (purQty == 0 && initQty > 0 && initAmount > 0)
        //    //{
        //    //    unitPrice = initAmount / initQty;
        //    //}
        //    if (initQty_Set == 0 && initUnitPrice_Set == 0)
        //    {
        //        unitPrice = (purQty + initQty) == 0 ? 0 : (initAmount + purAmount) / (purQty + initQty);
        //    }
        //    else if (initQty_Set != 0 && initUnitPrice_Set != 0)
        //    {

        //        unitPrice = (purQty + initQty_Set) == 0 ? 0 : (initUnitAmount_Set + purAmount) / (purQty + initQty_Set);
        //    }
        //    else
        //    {
        //        unitPrice = (purQty + initQty) == 0 ? 0 : (initAmount + purAmount) / (purQty + initQty);
        //    }

        //    return unitPrice;
        //}
        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
